<?php

declare(strict_types=1);

namespace App\Common\Helpers;

use App\Common\Constants\StorageModeConstants;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;
use Mine\Exception\NormalStatusException;
use function Symfony\Component\String\u;

class QrCode
{
    protected CommonUpload $commonUpload;

    public function __construct(CommonUpload $mxUpload)
    {
        $this->commonUpload = $mxUpload;
    }

    public function generation(array $config = [],$storageMode = StorageModeConstants::LOCAL)
    {
        $data = \Hyperf\Collection\data_get($config,'data');
        $size = \Hyperf\Collection\data_get($config,'size',300);
        $margin = \Hyperf\Collection\data_get($config,'margin',10);
        $writer = new PngWriter();

        $qrCode = new \Endroid\QrCode\QrCode(
            $data,
            new Encoding('UTF-8'),
            ErrorCorrectionLevel::Low,
            $size,
            $margin,
            RoundBlockSizeMode::Margin

        );
//            ->setForegroundColor(new Color(53, 73, 94))
//            ->setBackgroundColor(new Color(255, 255, 255));

        $logo = \Hyperf\Collection\data_get($config,'logo');
        $logoSource=null;
        if(!empty($logo)){
            $logoSource = new Logo($logo,50,50,true);
        }

        $label = \Hyperf\Collection\data_get($config,'label');
        if(!empty($label)){
            $label = Label::create($label)
                ->setTextColor(new Color(255, 0, 0));
        }

        $result = $writer->write($qrCode, $logoSource, $label);

        $url = $this->commonUpload->setStorageMode($storageMode)->uploadWrite($result->getString());

        if($storageMode == StorageModeConstants::OSS){
            $url = config('file.storage.oss.domain','').$url;
            return $url;
        }

        return BASE_PATH.'/public'.$url;
    }

    /**
     * 生成一个随机内容的二维码，并嵌入指定 Logo
     *
     * @param array $config 可选配置项（可包含 logo）
     * @param int $storageMode 存储方式（本地/OSS）
     * @return string 二维码访问地址
     */
    public function generationRandomQrCodeWithLogo(array $config = [],$fileType='base64'): string
    {
        // 1. 生成随机内容（例如：前缀 + 8位随机码）
        $randomData = 'lock_' . $this->generateRandomString(8); // 如 lock_abcd1234
        $config['data'] = $config['data'] ?? $randomData;

        // 2. 设置默认尺寸和边距（可被 config 覆盖）
        $config['size'] = $config['size'] ?? 300;
        $config['margin'] = $config['margin'] ?? 10;

        // 3. 检查是否传入了 logo
        if (isset($config['logo'])) {
            // 如果传入了 logo 路径，则使用该 logo
            $logoPath = $config['logo'];
            if (empty($logoPath)) {
                throw new NormalStatusException('请传入正确的 logo 路径');
            }
        }
        $path=$this->generation($config, StorageModeConstants::LOCAL);
        $imageData = base64_encode(file_get_contents($path));
        $ext = pathinfo($path, PATHINFO_EXTENSION);
        $base64code = 'data:image/'.$ext.';base64,' . $imageData;
        return $base64code;
    }

    /**
     * 生成指定长度的随机字符串
     *
     * @param int $length
     * @return string
     */
    private function generateRandomString(int $length = 10): string
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

}